import { Form, Input, message, Modal, Radio, TreeSelect } from "antd";
import * as LucideIcon from "lucide-react";
import { useEffect, useState } from "react";
import {
  apiAddPermission,
  apiModifyPermission,
  apiPermissionTree,
} from "~/api";
import type { IPermission } from "~/api/login/type";
import { transTreeToAntdTreeData } from "~/utils/ui.util";

interface Props {
  defaultParentId?: number;
  visible?: boolean;
  permission?: IPermission | null;
  onCancel?: () => void;
  onOk?: (values: Partial<IPermission>) => void;
}

export default function PermissionModal(props: Props) {
  const [form] = Form.useForm<Partial<IPermission>>();
  const [treeData, setTreeData] = useState<IPermission[]>([]);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      try {
        const fieldsValue = await form.validateFields();
        if (props.permission?.id) {
          await apiModifyPermission(props.permission.id, fieldsValue);
        } else {
          await apiAddPermission(fieldsValue);
        }
        props.onOk?.({
          id: props.permission?.id,
          ...fieldsValue,
        });
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      }
    },
  };

  const _fetch = {
    init: async () => {
      const resp = await apiPermissionTree();
      setTreeData([
        {
          label: "~ /",
          value: 0,
          title: "根节点",
        },
        ...transTreeToAntdTreeData(resp),
      ]);
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.resetFields();
    if (props.defaultParentId) {
      form.setFieldValue("parentId", props.defaultParentId);
    }
    if (props.permission) {
      form.setFieldsValue(props.permission as any);
    }
  }, [props.permission, props.visible, props.defaultParentId]);

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <Modal
      title={props.permission ? "编辑权限" : "新增子权限"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
    >
      <Form form={form} layout={"vertical"}>
        <Form.Item label="父权限" name={"parentId"}>
          <TreeSelect
            showSearch
            placeholder="请选择父权限"
            allowClear
            treeDefaultExpandAll
            treeLine={true}
            treeData={treeData}
            treeNodeLabelProp={"label"}
            disabled={!!props.defaultParentId}
          />
        </Form.Item>
        <Form.Item label="权限名称" name={"name"} required>
          <Input />
        </Form.Item>
        <Form.Item label="权限KEY（X_XX_XXX）" name={"key"} required>
          <Input />
        </Form.Item>
        <Form.Item label="访问路径" name={"path"}>
          <Input />
        </Form.Item>
        <div className="grid grid-cols-2 gap-4">
          <Form.Item label="类型" name={"type"}>
            <Radio.Group
              options={[
                {
                  value: 1,
                  label: "页面",
                },
                {
                  value: 2,
                  label: "功能",
                },
              ]}
            />
          </Form.Item>
          <Form.Item label="是否显示" name={"show"}>
            <Radio.Group
              options={[
                {
                  value: false,
                  label: <LucideIcon.EyeOffIcon />,
                },
                {
                  value: true,
                  label: <LucideIcon.EyeIcon />,
                },
              ]}
            />
          </Form.Item>
          <Form.Item label="图标（lucide-icon）" name={"icon"}>
            <Input />
          </Form.Item>
          <Form.Item label="排序" name={"sort"}>
            <Input />
          </Form.Item>
        </div>

        <Form.Item label="备注" name={"remark"}>
          <Input.TextArea />
        </Form.Item>
      </Form>
    </Modal>
  );
}
